package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioProperties minioProperties;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {

        InputStream inputStream = file.getInputStream();

        // 拼接服务器上的文件路径
        String timePath = new DateTime().toString("/yyyy/MM/dd/");
        String originalFilename = file.getOriginalFilename();// a.png
        String imgName = UUID.randomUUID().toString().replace("-","") + originalFilename;
        String objectName = timePath + imgName;

        // 服务客户端上传
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .stream(inputStream,file.getSize(),-1)
                .object(objectName)
                .bucket(minioProperties.getBucketName())
                .build();
        minioClient.putObject(putObjectArgs);

        // bug
        // int i = 1/0;

        // 返回url
        return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() +objectName;// 访问图片的url
    }
}
